import type { Directive } from 'vue'

/**
 * 只允许输入数字/小数
 */
export default {
  mounted(el, binding, vNode: any) {
    let content: number | string

    let arg_precision = 0 //默认保留至整数
    if (typeof binding.value?.max === 'number') {
      arg_precision = parseFloat(binding.value.precision)
    }

    let arg_max: number | undefined
    let arg_min: number | undefined

    if (typeof binding.value?.max === 'number') {
      arg_max = parseFloat(binding.value.max)
    }
    if (typeof binding.value?.min === 'number') {
      arg_min = parseFloat(binding.value.min)
    }
    // 设置输入框的值,触发input事件,改变v-model绑定的值
    const setVal = (val: number | string) => {
      vNode.ctx.emit('update:modelValue', val)
    }
    const reg = /\d|\./
    //按键按下=>只允许输入 数字/小数  点
    el.addEventListener('keypress', (e: KeyboardEvent) => {
      const inputKey = e.key

      content = (e!.target! as EventTarget & { value: string }).value

      if (arg_precision === 0 && inputKey === '.') {
        e.preventDefault()
        return
      }

      if (
        (content === '' || content === null || content === undefined) &&
        inputKey === '.'
      ) {
        e.preventDefault()
        return
      }

      if (arg_max && +(content + inputKey) > arg_max) {
        e.preventDefault()
        return
      }
      if (arg_min && +(content + inputKey) < arg_min) {
        e.preventDefault()
        return
      }

      if (!reg.test(inputKey) && !e.ctrlKey) {
        e.preventDefault()
        return
      }

      //已有小数点,再次输入小数点
      if (content.includes('.') && inputKey === '.') {
        e.preventDefault()
      }
    })

    el.addEventListener('input', (e: InputEvent) => {
      if (e.data && !reg.test(e.data)) {
        //只允许输入 数字/小数，不允许输入其他字符
        e.preventDefault()

        const value =
          vNode.ctx.props.modelValue + e.data.replace(/[^0-9.]/g, '')

        let inputDom = el.tagName === 'INPUT' ? el : el.querySelector('input')
        const prependDom = el.querySelector('.el-select')
        if (prependDom) {
          inputDom = el.querySelector(
            '.el-input-group__prepend+.el-input__wrapper input'
          )
        }

        inputDom.value = value
        setVal(value)
      }
    })

    //失去焦点=>保留指定位小数
    arg_precision &&
      el.addEventListener('focusout', (e: KeyboardEvent) => {
        content = parseFloat(
          (e!.target! as EventTarget & { value: string }).value
        )
        const value = content.toFixed(arg_precision)

        if (!isNaN(+value)) setVal(value)
      })
  }
} as Directive
